export default {
  namespaced:true,
  state:()=>({
      // 购物车的数组，用来存储购物车中每个商品的信息对象
        // 每个商品的信息对象，都包含如下 6 个属性：
        // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart:JSON.parse(uni.getStorageSync('cart')||'[]')
  }),
  mutations:{
    addCart(state,goods){
      const findResult=state.cart.find(item=>item.goods_id===goods.goods_id)
      if(!findResult){
        state.cart.push(goods)
      }else {
        findResult.goods_count++
      }
      this.commit('cart/saveStorageCart')
    },
    updateCart(state,goods){
      const findResult=state.cart.find(item=>item.goods_id===goods.goods_id)
      if(findResult){
        findResult.goods_state=!goods.goods_state
      }
     this.commit('cart/saveStorageCart')
    },
    updateCartCount(state,goods){
        const findResult=state.cart.find(item=>item.goods_id===goods.goods_id)
        if(findResult){
          findResult.goods_count=goods.goods_count
        }
         this.commit('cart/saveStorageCart')
    },
    toggleAllCheck(state,flag){
      state.cart.forEach(item=>{
        item.goods_state=flag
      })
       this.commit('cart/saveStorageCart')
    },
    removeCartItem(state,goods_id){
     state.cart=state.cart.filter(item=>item.goods_id!==goods_id)
      this.commit('cart/saveStorageCart')
    },
    saveStorageCart(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    }
  },
  getters:{
    infos(state){
      return state.cart.reduce((sum,item)=>sum+item.goods_count,0)
    },
    selectCheckCart(state){
      return state.cart.filter(item=>item.goods_state)
    },
    selectAllCart(state){
      return state.cart.every(item=>item.goods_state)
    },
    selectCount(state,getters){
      return getters.selectCheckCart.reduce((sum,item)=>sum+item.goods_count,0)
    },
    selectPrice(state,getters){
      return getters.selectCheckCart.reduce((sum,item)=>sum+item.goods_count*item.goods_price,0)
    }
  }
}